var roleManage = function() {

	var _init = function() {

		// 表单验证
		function validate(value, type) {
			// 字段值
			var value = $.trim(value);

			// 非空验证
			if (type === 'require') {
				return !!value;
			}
			// 手机号验证
			if (type === 'phone') {
				return /^1\d{10}$/.test(value);
			}
			// 邮箱验证
			if (type === 'email') {
				return /^(\w)+(\.\w+)*@(\w)+((\.\w{2,3}){1,3})$/.test(value);
			}
		}
		;

		// 关闭弹框
		$(".modal").on('hidden.bs.modal', function(e) {
			$('.modal .help-block').html(''); // 清空提示
//			$('.modal input').val(''); // 清空 input
		});
		// 添加
		/*$('#btn_new_role').click(function(event) {
			$('#modal_new_role').modal('show');
		});*/
		
		
		// 确定添加
		$('#modal_sure_new').click(function() {
			  var _data = $("#tenant_form").serializeObject();
			var name = $('#modal_new_role [name="input_name"]').val();
			var openWeek = _data.openWeek+"";
			/*$('#modal_new_role [name="openWeek"]:checked').each(function(){
				openWeek += $(this).val()+',';
			});*/
			var phone = $('#modal_new_role [name="input_phone"]').val();
			var openTime = $('#modal_new_role [name="input_openTime"]').val();
			var closeTime = $('#modal_new_role [name="input_closeTime"]').val();

			var address = $('#modal_new_role [name="input_address"]').val();
			
			var templateId = $('#modal_new_role [name="templateId"]').val();
			 var imgUrl= $('[name="imgUrl"]')[0].src; 

			var province = $('#modal_new_role [name="province"]').val();

			var city = $('#modal_new_role [name="city"]').val();
			var district = $('#modal_new_role [name="district"]').val();
			
			var introduction = $('#modal_new_role [name="introduction"]').val();
			
			var addressGeo = $('#modal_new_role [name="addressGeo"]').val();

			var id=$('#modal_new_role [type="hidden"]').val();

			/*var newDate =timeParse(openTime);
			var newDate1 =timeParse(closeTime);*/

			var param={"name":name,"openWeek":_data.openWeek+"","phone":phone,"openTime":openTime,"address":address,"closeTime":closeTime,
				"templateId":templateId,"imgUrl":imgUrl,"province":province	,"city":city,"id":id,"addressGeo":addressGeo,"district":district};
					
			if (!validate(name, 'require')) {
				$('#modal_new_role .help-block').html('请填写店铺名称'); 
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}else{
				var reg = /^(\w|[\u4E00-\u9FA5])*$/; 
				if(!name.match(reg)) 
				{ 
					$('#modal_new_role .help-block').html('店铺名称只允许为英文，数字和汉字的混合,\n请检查是否前后有空格或者其他符号');
					$("#modal_new_role .help-block").attr("style","color:red;");
				return ; 
				} 
			}if(!imgUrl){
				$('#modal_new_role .help-block').html('请上传logo');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			} 
			if(imgUrl.indexOf(window.location.pathname)>-1){
				$('#modal_new_role .help-block').html('请上传logo');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
		     }
		/*	if (!validate(phone, 'require')) {
				$('#modal_new_role .help-block').html('请填写电话');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(province, 'require')) {
				$('#modal_new_role .help-block').html('请选择省份');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(city, 'require')) {
				$('#modal_new_role .help-block').html('请选择城市');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(district, 'require')) {
				$('#modal_new_role .help-block').html('请选择区');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(address, 'require')) {
				$('#modal_new_role .help-block').html('请填写店铺地址');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(addressGeo, 'require')) {
				$('#modal_new_role .help-block').html('请选择地图标记');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}
			if (!_data.openWeek  ) {
				$('#modal_new_role .help-block').html('请选择营业天'); 
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(openTime, 'require')) {
				$('#modal_new_role .help-block').html('请填写营业时间');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(closeTime, 'require')) {
				$('#modal_new_role .help-block').html('请填写营业时间');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}if (!validate(introduction, 'require')) {
				$('#modal_new_role .help-block').html('请填写简介');
				$("#modal_new_role .help-block").attr("style","color:red;");
				return;
			}	var Strs = openTime.split(":");
			    var Strs1 = closeTime.split(":");
			    var num1=Strs[0]+Strs[1];
			    var num2=Strs1[0]+Strs1[1];
			    if(Number(num1)>=Number(num2)){
			    	$('#modal_new_role .help-block').html('开始时间应小于结束时间');
					$("#modal_new_role .help-block").attr("style","color:red;");
					return;
			    }*/
		
			/*if (!validate(phone, 'phone')) {
				$('#modal_new_role .help-block').html('电话格式不正确，请修改');
				return;
			}*/ else {
				var _type = id == null||id == '' ? "put" : "post";
				$.ajax({
					url : '/a/sys/tenant',
					type : _type,
					dataType : 'json',
					contentType:"application/json; charset=utf-8",
					data : JSON.stringify(param),
				}).done(function(data) {
					if (data.status === '1') {
						 console.log('保存成功！');
							$('#modal_new_role .help-block').html("保存成功！"); 
							$("#modal_new_role .help-block").attr("style","color:green;");
							 setTimeout(function(){$('#modal_new_role .help-block').html("");},5000);//5秒后执行该方法
						/*	$('body,html').animate({scrollTop:0},200);
        					return false;*/
					} else if (data.status === '2') {
//						错误
						$('#modal_new_role .help-block').html(data.message); // 返回错误信息
						$("#modal_new_role .help-block").attr("style","color:red;");

					}
				});
			}
		});



	}

	return {
		init : function() {
			_init();
		}

	};

}();

//获取时间
$(".data input[type='checkbox']").each(function(){
	if ($(this).is(":checked")) {
		$(this).parent("label").addClass("active");
	}
});
$(".data label").click(function(){
	if ($(this).is(".active")) {
		$(this).removeClass("active");
		$(this).find("input[type='checkbox']").attr("checked",false);
		return false;
	}else{
		$(this).addClass("active");
		$(this).find("input[type='checkbox']").attr("checked",true);
		return false;
	}
});

$("#add-text").change(function(){
	$("#add-text1").val("");
	$("#add-text1").attr("value","");
});

$("#distpicker select").change(function(){
	$("#add-text1").val("");
	$("#add-text1").attr("value","");
});
// 百度地图API功能
var map = new BMap.Map("allmap");
map.centerAndZoom("武汉",15); 
map.enableScrollWheelZoom(true);
$(".btn-map").click(function(){
	var address = $("#distpicker option:checked").text();
	
	var addtext = $("#add-text").val();
	var addtext2 = $("#add-text1").val();
	var addresstext = address+addtext;
	console.log(address+addtext);
	if(addtext2 != '') {
		console.log("有经纬度");
		$("#modal_map").modal('show');
		
		var d = addtext2.split(",");
	    if (d[0] && d[0].split(".")[0].length > 5 && d[1] && d[1].split(".")[0].length > 5) {
	        var f = projection.pointToLngLat(new BMap.Pixel(d[0], d[1]));
	        d = [f.lng, f.lat]
	    }
		//console.log(d);
		map.clearOverlays();
		var new_point = new BMap.Point(d[0], d[1]);
		var marker = new BMap.Marker(new_point);  // 创建标注
		map.addOverlay(marker);              // 将标注添加到地图中
		map.panTo(new_point);  
		map.centerAndZoom(new_point, 16);
		map.panBy(280,165);
		console.log(new_point);
		
	}else if(addtext != "" && address != ""){
		console.log("有省市有详细地址没有经纬度");
		$("#modal_map").modal('show');
		
		var local = new BMap.LocalSearch(map, {
			renderOptions: {
				map: map,
				panel: "results",//结果容器id  
				autoViewport: true,   //自动结果标注  
				selectFirstResult: true  , //指定到第一个目标 
				enableRouteSearchBox: true,
				enableRouteInfo:true
			},     
		    pageCapacity: 10,
		    onMarkersSet: function(res) {
	            res.forEach(function(e, i) {
	                let marker = e.marker;
	                var point = new BMap.Point(e.point.lng, e.point.lat);
	                map.centerAndZoom(point, 16);
	            	console.log(e.point.lng, e.point.lat);
	                $("#add-text1").val(e.point.lng + ','+ e.point.lat);
	                $("#add-text1").attr("value",e.point.lng + ','+ e.point.lat);
	                var geoc = new BMap.Geocoder();
	                marker.addEventListener("click", function() {
	                	var pt = e.point;
				            geoc.getLocation(pt, function(rs){
				              console.log('rs',rs.address);
				              //$("#add-text").val(rs.address);
				        });
	                    $("#add-text1").val(e.point.lng + ','+ e.point.lat);
	                    $("#add-text1").attr("value",e.point.lng + ','+ e.point.lat);
	                    
	                    $('#modal_map').modal('hide');
	                });
	            })
	        }
		});
		local.search(address+addtext);
		//console.log(addtext);
	}else if(addtext == "" && address != "" ){
		console.log("有省市没有详细地址没有经纬度");
		$("#modal_map").modal('show');
		//单击获取点击的经纬度
		map.centerAndZoom(address,13);
		map.clearOverlays();
		var geoc = new BMap.Geocoder();
		map.addEventListener("click",function(e){
			var pt = e.point;
	            geoc.getLocation(pt, function(rs){
	              console.log('rs',rs.address);
	              //$("#add-text").val(rs.address);
	        });
			$("#add-text1").val(e.point.lng + ','+ e.point.lat);
			$("#add-text1").attr("value",e.point.lng + ','+ e.point.lat);
			
			$('#modal_map').modal('hide');
		});
	}else if(address == "" ){
		alert("请选择省市");
	}else{
		console.log("请选择");
	}
	
}); 
/*
页面加载完毕 发起请求获取七牛token，通过前台传到七牛
*/
function getTokenMessage() {
	var url="";
	var qiniupercent="";
	var uploader="btn-uploader";
	var pickfiles="pickfiles";
	$.ajax({
		url: '/a/qiniu/uptoken',
		type: 'POST',
		data: {},
		cache: false,
		contentType: false,    //不可缺
		processData: false,    //不可缺
		dataType : 'json',
		success: function (data) {
			var obj = data;
			uploaderReady(obj.uptoken,url,qiniupercent,uploader,pickfiles);
		  }
		});
};
$(function() {
	roleManage.init();
	  getTokenMessage();
	
});